﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SubstringSearcher.Model
{
    public class SubstringSearcher
    {
        public static string GetFirstLineContaining(StreamReader reader, string substring)
        { 
            while (true)
            {
                string currentLine = reader.ReadLine();
                if (currentLine == null)
                {
                    return null;
                }

                if (currentLine.Contains(substring))
                {
                    return currentLine;
                }
            }
        }
        
        public delegate void ReportPrinter(string currentFileName, StreamWriter writer);
        
        public static void ForeachFileInDirectory(string dir, StreamWriter writer, ReportPrinter reportPrinter)
        {
            string[] fileNames = Directory.GetFiles(dir);

            foreach (string fileName in fileNames)
            {
                reportPrinter(fileName, writer);
            }
        }

        public static void ForeachFileInDirectoryAndSubdirectories(string dir, StreamWriter writer, ReportPrinter reportPrinter)
        {
            ForeachFileInDirectory(dir, writer, reportPrinter);

            string[] subdirNames = Directory.GetDirectories(dir);
            foreach (string subdirName in subdirNames)
            {                
                ForeachFileInDirectoryAndSubdirectories(subdirName, writer, reportPrinter);
            }
        }
    }
}
